package com.xianyun.book.command;

import com.alibaba.cola.dto.Response;
import com.alibaba.cola.exception.Assert;
import com.xianyun.book.domain.book.Book;
import com.xianyun.book.domain.gateway.BookGateway;
import com.xianyun.book.dto.BookAddCmd;
import com.xianyun.book.gatewayimpl.database.BookMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import javax.validation.Valid;
import java.math.BigDecimal;


/**
 * 书籍保存接口
 * @author ytt
 */
@Slf4j
@Component
public class BookAddCmdExe {
    
    @Resource
    private BookGateway bookGateway;
    @Resource
    private BookMapper bookMapper;

    public Response execute(@Valid BookAddCmd cmd){
        log.info("新书上架: 书名:{},ISBN:{} --等待校验",cmd.getBookName(),cmd.getIsbn());
        Assert.isTrue(null == bookMapper.selectBookByIsbn(cmd.getIsbn()),"该书籍已存在无需添加!");
        Book saveBookInfo = new Book();
        saveBookInfo.setImgUrl(cmd.getImgUrl());
        saveBookInfo.setPrice(BigDecimal.valueOf(cmd.getOriginalPrice()));
        saveBookInfo.setDesc(cmd.getBookDesc());
        saveBookInfo.setBookTypes(bookGateway.conversionTypeList(cmd.getBookTypes()));
        BeanUtils.copyProperties(cmd,saveBookInfo);
        bookGateway.save(saveBookInfo);
        return Response.buildSuccess();
    }
}
